#include "Socket.hpp"
#include "Protocol.hpp"
#include <iostream>
#include <unistd.h>
#include <memory>

#include "TcpServer.hpp"
#include"Calculate.hpp"
using namespace std;
using namespace Network;
using namespace Protocol;
using namespace CalCulate;


void HandlerRequest(Socket *sock)
{
    Calculate calculate;//计算器

    unique_ptr<Factory> factory = make_unique<Factory>();
    auto req = factory->BuildRequest();

    string inbufferstream;
    while (true)
    {
        // 1.读取报文
        if (!sock->Recv(&inbufferstream, 1024))break;

        // 2.分析字节流，看是否有一个完整的报文
        string message;
        if (!Decode(inbufferstream, &message))continue;
        // 3.我一定读到了一个完整的报文，可以进行反序列化了
        if(!req->Deserialize(message))break;//反序列化

        //4.业务处理了
        auto resp=calculate.Cal(req);

        //5.序列化
        string send_string;
        resp->Serialize(&send_string);//"result code"

        //6.构建完成字符串级别的响应报文（添加报头）
        send_string=Encode(send_string);

        //7.
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        cout << "Usage:\n     ./udp_echo_server <port>" << endl;
        return 0;
    }

    uint16_t localport = atoi(argv[1]);

    unique_ptr<TcpServer> svr(new TcpServer(localport, HandlerRequest));
    svr->Loop();
}
